package com.cqs.example.websocket.stomp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;

@Controller
public class GreetingController {


    @Autowired
    private SimpMessagingTemplate messagingTemplate;


    /**
     * 广播
     * @param message
     * @return
     * @throws Exception
     */
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting broadcast(HelloMessage message) throws Exception {
        Thread.sleep(1000); // simulated delay
        System.out.println("broadcast message:" + message.getName());
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }
    /**
     * 点对点 根据userId进行区分
     * @param message
     * @return
     * @throws Exception
     */
    @MessageMapping("/hello/u/{userId}")
    @SendTo("/topic/greetings/u/{userId}")
    public Greeting pointToPoint(HelloMessage message) throws Exception {
        Thread.sleep(200);
        System.out.println("pointToPoint message:" + message.getName());
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }

    @MessageMapping("/helloUser")
    @SendToUser("/topic/greetingsUser")
    public Greeting greetingUser(HelloMessage message) throws Exception {
        Thread.sleep(200);
        System.out.println("greetingUser message:" + message.getName());
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }





}
